//
//  DoneOrderView.m
//  OrderSeat
//
//  Created by 王威 on 13-12-24.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "ShopCollectView.h"
#import "MyOrderCell.h"
#import "MyOrderViewController.h"
#import "OrderDetailViewController.H"
#import "ShopInfoCell.h"
#import "ShopHomeViewController.h"
#import "MyCollectViewController.h"

@implementation ShopCollectView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _dataSource = [[ShopCollectDataSource alloc] initWithView:self];
        [self initViews];
        [self autoPullRefresh];
    }
    return self;
}

- (void)initViews
{
    _orderTable = [[UITableView alloc] initWithFrame:self.bounds];
    _orderTable.backgroundColor = [UIColor clearColor];
    _orderTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    _orderTable.delegate = _dataSource;
    _orderTable.dataSource = _dataSource;
    [self addSubview:_orderTable];
    
    [self createHeaderView];
}

- (void)autoPullRefresh
{
    [_orderTable setContentOffset:CGPointMake(0, -75) animated:YES];
    [self performSelector:@selector(doPullRefresh) withObject:nil];
}

//执行下拉刷新
-(void)doPullRefresh {
    [_refreshHeaderView egoRefreshScrollViewDidScroll:self.orderTable];
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self.orderTable];
}

-(void)createHeaderView {
    if (_refreshHeaderView && [_refreshHeaderView superview]) {
        [_refreshHeaderView removeFromSuperview];
    }
	_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:
                          CGRectMake(Zero, Zero - ScreenHeight, ScreenWidth, ScreenHeight)];
    _refreshHeaderView.delegate = self;
    
	[_orderTable addSubview:_refreshHeaderView];
    [_refreshHeaderView refreshLastUpdatedDate];
}

#pragma mark data reloading methods that must be overide by the subclass
-(void)beginToReloadData:(EGORefreshPos)aRefreshPos
{
	_reloading = YES;
    if (aRefreshPos == EGORefreshHeader)
	{
        [self performSelector:@selector(refreshView) withObject:nil afterDelay:2.0];
    }
}

//刷新调用的方法
-(void)refreshView
{
    _dataSource.pageNumber = 1;
    [_dataSource fetchShop];
}

-(void)finishedLoadData
{
    [_orderTable reloadData];
    [self finishReloadingData];
    
    [self addEmptyText];
}

- (void)addEmptyText
{
    if (_dataSource.shopList.count == 0) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, self.width, 30)];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:20];
        label.textColor = [UIColor grayColor];
        label.text = @"没有数据显示";
        label.tag = 1234;
        [self addSubview:label];
    }else {
        UIView *view = [self viewWithTag:1234];
        [view removeFromSuperview];
    }
}

- (void)finishReloadingData
{
	_reloading = NO;
    
	if (_refreshHeaderView) {
        [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_orderTable];
    }
}

#pragma mark -
#pragma mark EGORefreshTableDelegate Methods
- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos
{
	[self beginToReloadData:aRefreshPos];
}

- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view
{
	return _reloading; // should return if data source model is reloading
}

// if we don't realize this method, it won't display the refresh timestamp
- (NSDate*)egoRefreshTableDataSourceLastUpdated:(UIView*)view
{
	return [NSDate date]; // should return date data source was last changed
}

#pragma 将分页加载的数据添加到tableview后面
- (void)appendTableWith:(NSMutableArray *)data
{
    for (int i = 0; i < [data count]; i++) {
        [_dataSource.shopList addObject:[data objectAtIndex:i]];
    }
    
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
    
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath *newPath = [NSIndexPath indexPathForRow:[_dataSource.shopList indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    
    [_orderTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    _moreLoading = NO;
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

#define RefreshTag 1001
#define LoadMoreTag 1002
#define RemoveTag 1003

@implementation ShopCollectDataSource

- (id)initWithView:(id)view
{
    self = [super init];
    if (self) {
        self.view = view;
        _shopList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

- (void)fetchShop
{
    NSString *url = [NSString stringWithFormat:API_COLLECT_DINNER, [AppSetting userName], _pageNumber];
    [self get:url tag:_pageNumber == 1 ? RefreshTag : LoadMoreTag];
}

- (void)removeWithId:(NSString *)shopId
{
    NSString *url = [NSString stringWithFormat:API_DEL_SHOP,shopId];
    [self get:url tag:RemoveTag];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@", request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    
    if ([[json objectForKey:@"error_code"] intValue] == 0) {
        NSDictionary *data = [json objectForKey:@"data"];
        
        if (request.tag == RefreshTag) {
            self.shopList = [data objectForKey:@"dinner"];
            [_view finishedLoadData];
        }
        
        if (request.tag == LoadMoreTag) {
            [_view appendTableWith:[data objectForKey:@"dinner"]];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    _pageNumber--;
    [_view finishedLoadData];
    [super requestFailed:request];
}

#pragma mark-=======================requestFinished回调========================================

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _shopList.count;
}
 
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellId = @"ShopInfoCell";
    
    ShopInfoCell *cell = (ShopInfoCell *)[tableView dequeueReusableCellWithIdentifier:CellId];
    
    if (cell == nil) {
        cell = [[ShopInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setBackgroundColor:[UIColor clearColor]];
    }
    
    NSDictionary *dic = [_shopList objectAtIndex:indexPath.row];
    [cell setContent:dic];
    
    return cell;
}
 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_shopList objectAtIndex:indexPath.row];
    NSString *shopId = [dic objectForKey:@"did"];
    
    ShopHomeViewController *shopHomeVC = [[ShopHomeViewController alloc] initWithId:shopId];
    [AppDelegate changeToShopTabBar:shopHomeVC];
    
    [self.view.collectVC.navigationController pushViewController:shopHomeVC animated:YES];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	if (_view.refreshHeaderView)
	{
        [_view.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	if (_view.refreshHeaderView)
	{
        [_view.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}

#pragma 分页加载
-(void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == _shopList.count-1) {
        if (!self.view.moreLoading) {
            _pageNumber++;
            [self fetchShop];
            
            self.view.moreLoading = YES;
        }
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSDictionary *dic = [_shopList objectAtIndex:indexPath.row];
        NSString *shopId = [dic objectForKey:@"id"];
        
        [_shopList removeObject:dic];
        [self removeWithId:shopId];
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

@end
